package com.wzh.mall.ssoclient2.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * @program: mall
 * @description:
 * @author: Mr.Wang
 * @create: 2021-10-09 07:59
 **/
@Controller
public class HelloController {


    @Value("${sso.server.url}")
    String ssoServerUrl;





    /**
      * @Description: 无需登录就可以访问
      * @Param: []
      * @return: java.lang.String
      * @Author: Mr.Wang
      * @Date: 2021/10/9
      * @Time: 8:01
      */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }


    // 要能感知这次是在ssoserver登陆成功返回回来的
    /**
      * @Description:
      * @Param: token:只要去ssoserver登录成功了就会带回来
      * @return: java.lang.String
      * @Author: Mr.Wang
      * @Date: 2021/10/9
      * @Time: 10:19
      */      
      
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token",required = false) String token){
        if (!StringUtils.isEmpty(token)){
            // 去ssoserver登录成功了就会带回来
            //TOD O,1、去ssoserver获取当前token真正对应的用户信息
            RestTemplate restTemplate=new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo:token=" + token, String.class);
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }

        Object loginUser=session.getAttribute("loginUser");
        if (loginUser==null){
            // 没有登录 跳转登陆服务器
            // 跳转过去以后，使用url上的查询参数标识我们自己是哪个页面
            //redirect_url=http://client1.com:8080/employees
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client2.com:8081/boss";

        }else {
            // 登陆了
            ArrayList<String> list = new ArrayList<>();
            list.add("张三");
            list.add("李四");
            model.addAttribute("emps",list);
            return "list";

        }


    }

}
